package com.etc.service.impl;

import com.etc.dao.PatientMapper;
import com.etc.entity.Patient;
import com.etc.service.TencentService;
import com.etc.util.RandomUtil;
import com.etc.util.TencentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class TencentServiceImpl implements TencentService {
    private static final Logger logger = LoggerFactory.getLogger(TencentServiceImpl.class);

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    PatientMapper patientMapper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean send(String phone) {
        //生成四位数验证码交腾讯云发送
        String code = RandomUtil.getFourBitRandom();

        //设置短信有效期
        String lifeTime = "2";
        //发送验证码
        boolean res = TencentUtil.SendCode("+86" + phone, code,lifeTime);

        if (res){
            //发送成功后将验证码放到Redis中设置存活时间2分钟
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return true;
        }else {
            //throw new GuliException(20001,"验证码发送失败");
            return false;
        }
    }

    @Override
    public boolean loginByCode(String phone,String code) {

        Object codeFromRedisRow = redisTemplate.opsForValue().get(phone);
        logger.debug("+++++++++row:"+codeFromRedisRow);
        //Integer codeInteger = (Integer) codeFromRedisRow;
        String codeFinal = String.valueOf(codeFromRedisRow);
        //logger.debug("++++++++++++codeInteger:"+codeInteger);
        //String codeFinal = String.valueOf(codeInteger);
        logger.debug("+++++++++++codeFinal:"+codeFinal);
        if(code.equals(codeFinal)){
//            redisTemplate.delete(phone);
            logger.debug("++++++++++++enter here");
            //登录成功，将就诊人对象存入session
            Patient p = new Patient();
            p.setPhone(phone);
            List<Patient> patients = patientMapper.findSelective(p);
            if(!patients.isEmpty()){
                request.getSession().setAttribute("patient",patients.get(0));
            }

            return true;
        }

        logger.debug("+++++++++++++enter there");
        return false;
    }

    @Override
    public boolean codeExist(String phone) {
        Object o = redisTemplate.opsForValue().get(phone);
        if(o!=null){
            return true;
        }



        return false;
    }


}
